package com.rongke.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.rongke.enums.MsgTypeEnum;
import com.rongke.enums.OrderStatusEnum;
import com.rongke.enums.PayTypeEnum;
import com.rongke.mapper.AccountMapper;
import com.rongke.mapper.IncomeFlowMapper;
import com.rongke.mapper.MuserMapper;
import com.rongke.model.*;
import com.rongke.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @AccountServiceImpl
 * @ServiceImpl
 * @version : Ver 1.0
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private MuserMapper muserMapper;
    @Autowired
    private MuserService muserService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderGoodsService orderGoodsService;
    @Autowired
    private MsgUserService msgUserService;
    @Autowired
    private IncomeFlowMapper incomeFlowMapper;
    @Autowired
    private MessageService messageService;
    @Override
    public Account selectAccountAndUserMess(Long id) {
        return accountMapper.selectAccountAndUserMess(id);
    }

    @Override
    public Account selectAccountByUserId(Long userId) {
       Account account=new Account();
        account.setMuserId(userId);
        Account account1=accountMapper.selectOne(account);

        return account1;
    }

    @Override
    public JSONObject updateRecomendUserAccount(Long recomendId, Long orderId) {
        JSONObject jsonObject = new JSONObject();
        Orders orders = ordersService.selectById(orderId);
        Integer payWay = orders.getPayType();
        BigDecimal money = orders.getTotalPrice().subtract(orders.getDeliveryMoney());
        if(orders.getPayType()== PayTypeEnum.YABI.getType()){
            jsonObject.put("code", "200");
            return jsonObject;
        }
        Double profitability=muserService.findProfitability(recomendId);
        if(profitability==null){
            jsonObject.put("code", "500");
            jsonObject.put("message", "该会员推荐人尚未设置获利比率");
            return jsonObject;
        }
        Account account = new Account();
        account.setMuserId(recomendId);
        Account recomendAccount = accountMapper.selectOne(account);
        //如果订单状态为待发货或已放货 则百夫长或千夫长或加盟商  不可用哆币余额增加
        if (orders.getOrderStatus() == OrderStatusEnum.WAIT_SHIP.getType() || orders.getOrderStatus() == OrderStatusEnum.DELIVERING.getType() || orders.getOrderStatus() == OrderStatusEnum.BUYTOGETHER.getType()) {
                recomendAccount.setUnavailableDuobi(recomendAccount.getUnavailableDuobi().add(money.multiply(new BigDecimal(String.valueOf(profitability)))));
            //如果订单状态为已完成、待评价  则百夫长或千夫长或加盟商  将不可用哆币余额转换为可用余额
        } else if (orders.getOrderStatus() == OrderStatusEnum.COMPLETE.getType() || orders.getOrderStatus() == OrderStatusEnum.PENDING_EVALUATION.getType()) {
                recomendAccount.setUnavailableDuobi(recomendAccount.getUnavailableDuobi().subtract(money.multiply(new BigDecimal(String.valueOf(profitability)))));
                recomendAccount.setDuoBi(recomendAccount.getDuoBi().add(money.multiply(new BigDecimal(String.valueOf(profitability)))));
                //总收益总额累加
                BigDecimal inCome = recomendAccount.getIncome().add(money.multiply(new BigDecimal(String.valueOf(profitability))));

            /******* 收到提成提示消息******/
            BigDecimal total_fee=money.multiply(new BigDecimal(String.valueOf(profitability)));
            if(total_fee.compareTo(BigDecimal.ZERO)==1){
                Message msg=messageService.selectTemplateMsgByMsgType(1);
                if(null!=msg){
                    String title=msg.getTitle();
                    String totalFee=total_fee.toString();
                    String content=msg.getContent()
                            .replace("#orderNumber#",orders.getOrderNumber())
                            .replace("#totalFee#",totalFee);
                    MsgUser msgUser=new MsgUser();
                    msgUser.setMuserId(recomendAccount.getMuserId());
                    msgUser.setTitle(title);
                    //"你刚刚收到来自订单号为 #orderNumber# 的提成收益，提成金额为：#totalFee#"
                    msgUser.setMsgContent(content);
                    msgUserService.insert(msgUser);
                }
            }
            /******* 收到提成提示消息******/


                recomendAccount.setIncome(inCome);
        }else {//订单为退款完成  将百夫长或千夫长或加盟商  将不可用哆币余额转换减掉
                recomendAccount.setUnavailableDuobi(recomendAccount.getUnavailableDuobi().subtract(money.multiply(new BigDecimal(String.valueOf(profitability)))));
        }
        accountMapper.updateById(recomendAccount);
        //记录该笔金额
        if (orders.getOrderStatus() == OrderStatusEnum.COMPLETE.getType() || orders.getOrderStatus()==OrderStatusEnum.PENDING_EVALUATION.getType()) {
            IncomeFlow selectOne = new IncomeFlow();
            selectOne.setOrderId(orderId);

            List<IncomeFlow> iFList = incomeFlowMapper.selectByCondition(selectOne);
            iFList.forEach(e->{
                e.setStatus(1);
                e.setUptDatetime(new Date());
                incomeFlowMapper.updateById(e);
            });


        } else if(orders.getOrderStatus() == OrderStatusEnum.WAIT_SHIP.getType() || orders.getOrderStatus() == OrderStatusEnum.DELIVERING.getType() || orders.getOrderStatus() == OrderStatusEnum.BUYTOGETHER.getType()){
            IncomeFlow incomeFlow = new IncomeFlow();
            incomeFlow.setMuserId(recomendId);
            incomeFlow.setIncome(money.multiply(new BigDecimal(String.valueOf(profitability))));
            incomeFlow.setOrderId(orderId);
            incomeFlow.setStatus(2);
            incomeFlow.setGmtDatetime(new Date());
            incomeFlowMapper.insert(incomeFlow);
        }else {
            EntityWrapper<IncomeFlow> ew=new EntityWrapper<>();
            ew.eq("order_id",orderId);
            ew.eq("status",2);
            incomeFlowMapper.delete(ew);
        }
        jsonObject.put("code", "200");
        return jsonObject;

    }

    @Override
    public List<Account> selectAllAccountAndUser(Map map) {

        return accountMapper.selectAllAccountAndUser(map);
    }

    @Override
    public Integer selectAccountAndUserNums(Map map) {
        return accountMapper.selectAccountAndUserNums(map);
    }

    @Override
    public List<Account> selectUserTeamList(Map map) {
        return accountMapper.selectUserTeamList(map);
    }

    @Override
    public Integer selectUserTeamListSize(Map map) {
        return accountMapper.selectUserTeamListSize(map);
    }
}
